package com.boc.news.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.boc.bus.control.BusOutputResult;
import com.boc.bus.control.ControlBus;
import com.boc.bus.control.IocBeans;
import com.boc.news.beans.json.JsonArray;

public class AjaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig servletConfig) throws ServletException {
		super.init();
		new IocBeans(servletConfig.getInitParameter("ajaxServer"));
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		ControlBus bus = new ControlBus();
		String serviceName[] = request.getParameter("SERVICENAME").split("\\.");
		Object bean = (Object) IocBeans.beanFactory.getBean(serviceName[0]);
		try {
			Enumeration rnames = request.getParameterNames();
			Map map = new HashMap();
			for (Enumeration e = rnames; e.hasMoreElements();) {
				String thisName = e.nextElement().toString();
				String thisValue = request.getParameter(thisName);
				if (!"SERVICENAME".equals(thisName))
					map.put(thisName, thisValue);
			}
			BusOutputResult result = (BusOutputResult) bus
					.invokeFactoryProxyClass(request, response, map, bean
							.getClass(), serviceName[1]);
			JsonArray json = new JsonArray();
			json.put(result.getResult());
			out.print(json);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (ArrayIndexOutOfBoundsException e) {
			e.printStackTrace();
		}
	}
}
